! function () {

	function ChatBox(id) {
		// 容器ID
		this.editor_id = id;

		// 配置项
		this.config = {
			// 唯一标识
			itemid: GenNonDuplicateID(),

			// 七牛云配置
			qiniu_accp: 'test/',

			//富文本框配置
			edtConfig: {
				//初始化toolbar
				// items: ['emoticons', 'insertfile', ''],
				items: ['emoticons', 'insertfile', ''],
				// width: '700px',
				minWidth: '200px',
				minHeight: '140px',
				// height: '300px',
				//2或1或0，2时可以拖动改变宽度和高度，1时只能改变高度，0时不能拖动
				resizeType: 0,
				//true时使用右键菜单，false时屏蔽右键菜单
				useContextmenu: false,
				filterMode: true,
				newlineTag: 'br'
			}
		}

		// 创建主体
		this.doms = initMain.call(this);

	}

	// 配置控件
	ChatBox.prototype.init = function (opts) {
		var self = this;

		// 七牛云配置
		(typeof opts.qiniu_accp == 'string') && (self.config.qiniu_accp = opts.qiniu_accp);

		//富文本框配置
		if (Object.prototype.toString.call(opts.edtConfig) === "[object Object]" && JSON.stringify(opts.edtConfig) !== '{}') {
			for (var key in opts.edtConfig) {
				self.config.edtConfig[key] = opts.edtConfig[key]
			}
		}
	}

	// 创建唯一标识
	function GenNonDuplicateID() {
		return Number(Math.random().toString().substr(3) + Date.now()).toString(36);
	}

	// 创建主体
	function initMain() {
		var self = this;

		var objs = {};

		//----------------------------------------------------------
		objs.areaDom = document.createElement("div");
		objs.areaDom.className = 'textarea-editor-box';
		//----------------------------------------------------------

		//----------------------------------------------------------
		objs.textareaDom = document.createElement("textarea");
		objs.textareaDom.id = "textarea-editor-" + self.config.itemid;
		objs.textareaDom.style.width = "100%";
		objs.textareaDom.style.height = "100%";
		//----------------------------------------------------------

		//----------------------------------------------------------
		// objs.aDom = document.createElement("a");
		// objs.aDom.href = "javascript:;";
		// objs.aDom.className = "textarea-editor-sendbtn";
		// objs.aDom.innerText = "发送";
		//----------------------------------------------------------

		//----------------------------------------------------------
		objs.imgIptDom = document.createElement("input");
		objs.imgIptDom.type = "file";
		objs.imgIptDom.accept = "image/*";
		objs.imgIptDom.style.display = "none";
		//----------------------------------------------------------

		//----------------------------------------------------------
		objs.fileIptDom = document.createElement("input");
		objs.fileIptDom.type = "file";
		objs.fileIptDom.style.display = "none";
		//----------------------------------------------------------

		//----------------------------------------------------------
		objs.areaDom.appendChild(objs.imgIptDom);
		objs.areaDom.appendChild(objs.fileIptDom);
		objs.areaDom.appendChild(objs.textareaDom);
		// objs.areaDom.appendChild(objs.aDom);
		//----------------------------------------------------------

		document.getElementById(self.editor_id).appendChild(objs.areaDom);

		//初始化富文本框
		KindEditor.ready(function (K) {
			//创建富文本框
			var editor = K.create('#' + objs.textareaDom.id, self.config.edtConfig);
			// var editor = K.create('#textarea-editor', self.config.edtConfig);
			editor.html('');

			window.CHAT_EDITOR = editor;
			window._K = K;

			//设置最外层div的尺寸，以便 "发送" 按钮定位
			objs.areaDom.style.width = self.config.edtConfig.width;
			objs.areaDom.style.height = self.config.edtConfig.height;

			//初始化选择图片和文件事件
			initChoose.call(self, editor);

			// 发送
			// objs.aDom.onclick = function () {
			//     handleClickSend.call(self, editor, K);
			// }

			//读取粘贴板内容
			readPaste.call(self, editor, K);

			//选择图片
			objs.imgIptDom.onchange = function (event) {
				handleClickChooseImg.call(self, event, K);
			}

			//选择文件
			objs.fileIptDom.onchange = function (event) {
				handleClickChooseFile.call(self, event, K);
			}

		})

		return objs;
	}

	//初始化选择图片和文件事件
	function initChoose(editor) {
		var self = this;
		//上传图片
		editor.clickToolbar('image', function () {
			var imgIpt = self.doms.imgIptDom;
			if (imgIpt) {
				imgIpt.click();
			}
		});
		//上传文件
		editor.clickToolbar('insertfile', function () {
			var imgIpt = self.doms.fileIptDom;
			if (imgIpt) {
				imgIpt.click();
			}
		});
	}

	//发送
	function handleClickSend(editor, K) {
		var self = this;
		//获取textarea的值
		var val = editor.html();
		if (val === '') {
			modal.tips("不能发送空白消息");
			return;
		}
		console.log(val)
	}

	//读取粘贴板内容
	function readPaste(editor, K) {
		var self = this;
		var dom = editor.edit.doc;
		dom.addEventListener("paste", function (e) {
			var ua = document.querySelector('#ua');
			// ua.innerHTML = e.clipboardData.getData("text/plain")
			setTimeout(function (e) {
				// ua.innerHTML = editor.text();
				// alert(editor.text())
				var str = editor.text();
				var bs64 = str.split('" alt=')[0].split(';base64,')[1];
				uploadBs64ToQiniu(bs64, function (res) {
					editor.html(res)
				})
			}, 500);

			if (!(e.clipboardData && e.clipboardData.items)) {
				return;
			}

			for (var i = 0, len = e.clipboardData.items.length; i < len; i++) {
				var item = e.clipboardData.items[i];
				if (item.kind === "string") {
					// kind=string分两类：text/plain，text/html
					// text/plain 为纯文本
					// if (item.type === "text/plain") {
					//     item.getAsString(function (str) {
					//         // str 是获取到的字符串
					//         K.appendHtml('#textarea-editor-' + self.config.itemid, str);
					//         console.log(str)
					//     })
					// }
					// // text/html html文本
					// if (item.type === "text/html") {
					//     item.getAsString(function (str) {
					//         // str 是获取到的html字符串
					//         K.appendHtml('#textarea-editor-' + self.config.itemid, str);
					//         console.log(str)
					//     })
					// }
				} else if (item.kind === "file") {
					// pasteFile就是获取到的文件
					var pasteFile = item.getAsFile();
					// 上传至七牛云
					uploadFileToQiniu.call(self, pasteFile, function (url) {
						var appendHtml = '<a href="' + url + '" rel="lightbox[roadtrip]">';
						appendHtml += '<img src="' + url + '" />';
						appendHtml += '</a>';
						K.appendHtml('#textarea-editor-' + self.config.itemid, appendHtml);
					});
				}
			}
		});
	}

	function uploadBs64ToQiniu(str, cb) {
		if (!str) return
		var self = this;
		var pic = str;
		var token = initUploadToken();
		var url = "http://upload-z2.qiniup.com/putb64/-1"
		//非华东空间需要根据注意事项 1 修改上传域名
		var xhr = new XMLHttpRequest();

		xhr.onreadystatechange = function () {
			if (xhr.readyState == 4) {
				try {
					var res = JSON.parse(xhr.responseText);
					var imgUrl = data_qiniu.domain + res.key;
					var appendHtml = '[图片=' + imgUrl + ']';
					// alert(appendHtml)
					cb(appendHtml)
					// K.appendHtml('#textarea-editor-' + self.config.itemid, appendHtml);
				} catch (err) {

				}
			}
		}
		xhr.open("POST", url, true);
		xhr.setRequestHeader("Content-Type", "application/octet-stream");
		xhr.setRequestHeader("Authorization", 'UpToken ' + token);
		xhr.send(pic)
	}

	//选择图片
	function handleClickChooseImg(event, K) {
		var self = this;
		var resultFile = event.target.files[0];
		if (resultFile) {
			// 上传至七牛云
			uploadFileToQiniu.call(self, resultFile, function (url) {
				var appendHtml = '<a href="' + url + '" rel="lightbox[roadtrip]">';
				appendHtml += '<img src="' + url + '" />';
				appendHtml += '</a>';
				K.appendHtml('#textarea-editor-' + self.config.itemid, appendHtml);
			});
		}

	}

	//选择文件
	function handleClickChooseFile(event, K) {
		var self = this;
		var resultFile = event.target.files[0];
		if (resultFile) {
			// 上传至七牛云
			uploadFileToQiniu.call(self, resultFile, function (url) {
				// 文件类型判断
				var appendHtml = '';
				if (resultFile.type.indexOf('image') != -1) {
					//图片
					// appendHtml= '<a href="' + url + '" rel="lightbox[roadtrip]">' + url + '</a>';
					appendHtml = '[图片=' + url + ']';
				} else {
					//其它文件
					appendHtml = '[文件=' + url + ']';
				}
				K.appendHtml('#textarea-editor-' + self.config.itemid, appendHtml);
			});
		}
	}

	//上传七牛云
	function uploadFileToQiniu(resultFile, callback) {
		var self = this;
		//用当前时间戳命名文件名
		var timeStamp = new Date().getTime();
		var fileName = resultFile.name;
		var idx = fileName.lastIndexOf(".");
		if (idx !== -1) {
			fileName = timeStamp + fileName.substring(idx, fileName.length);
		} else {
			fileName = timeStamp;
		}

		//读文件
		var files = doReadFile(resultFile, resultFile.type, fileName);
		var key = self.config.qiniu_accp + fileName;
		var token = initUploadToken();
		var putExtra = {
			fname: fileName,
			params: {},
			mimeType: [] || null
		};
		var config = {
			useCdnDomain: true,
			region: qiniu.region.z2
		};
		//上传
		var observable = qiniu.upload(files, key, token, putExtra, config);
		var observer = {
			next(res) {
				// console.log(res)
			},
			error(err) {
				// console.log(err)
			},
			complete(res) {
				if (res.key) {
					// 文件路径
					var file_url = data_qiniu.domain + res.key;
					callback(file_url);
				} else {
					//失败，1.6s后重试
					setTimeout(function () {
						uploadFileToQiniu(resultFile);
					}, 1600);
				}
			}
		}
		var subscription = observable.subscribe(observer);

	}

	// 读文件
	function doReadFile(value, type, name) {
		var blob;
		if (typeof window.Blob == "function") {
			blob = new Blob([value], {
				type: type
			});
		} else {
			var BlobBuilder = window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder;
			var bb = new BlobBuilder();
			bb.append(value);
			blob = bb.getBlob(type);
		}
		return blob;
	}

	// export
	window.ChatBox = ChatBox;
}();